package com.cloud.prac.config;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

/**
 * TemplateHelper
 *
 * @author H
 * @version 1.0
 * @date 2024-04-29 16:52
 */
@Component
public class TemplateHelper {

    private static final Configuration CONFIGURATION;
    private static final StringTemplateLoader STRING_TEMPLATE_LOADER;

    static {
        CONFIGURATION = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        STRING_TEMPLATE_LOADER = new StringTemplateLoader();
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateLoader(STRING_TEMPLATE_LOADER);
    }

    public String toHtmlString(String templateCode, Map<String, Object> params) {
        try {
            return FreeMarkerTemplateUtils.processTemplateIntoString(CONFIGURATION.getTemplate(templateCode), params);
        } catch (IOException | TemplateException e) {
            throw new RuntimeException(e);
        }
    }

    public void put(String name, String templateContent) {
        STRING_TEMPLATE_LOADER.putTemplate(name, templateContent);
    }


}
